package com.njrsrc.android.app;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.flurry.android.FlurryAgent;
import com.njrsrc.R;
import com.njrsrc.android.bean.UserInfo;
import com.njrsrc.android.tasks.UploadPicTask;
import com.njrsrc.android.views.TitleBar;
import com.njrsrc.common.url.FileDirProvider;
import com.njrsrc.common.url.RequestUrlProvider;
import com.njrsrc.common.utils.Helpers;
import com.njrsrc.common.utils.MsgID;

/**
 * 主页面
 * 
 * @author Administrator
 * 
 */
public class MainActivity extends BaseActivity implements OnClickListener {
	private TitleBar mBar;

	private FrameLayout menu_1;
	private FrameLayout menu_2;
	private FrameLayout menu_3;
	
	private ImageView headerView;
	
	private PopupWindow summaryWindow;	//the summary window
	
	private static final int CAMERA = 1;
	private static final int PICTURE = 2;
	private boolean isTakePicture = false;
	private String picPath;
	private UserInfo loginInfo;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == MsgID.HEAD_DOWNLOAD_SUCCESS) {
				String fileName = (String) msg.obj;
				Drawable mDrawable = new BitmapDrawable(Helpers.scaleBitmap(fileName, 90, 90));
						//Helpers.getDrawableBySDPath(fileName);
				if (mDrawable == null) {
					return;
				}
				headerView.setBackgroundDrawable(mDrawable);
			}
			
			switch (msg.what) {
			case 6:
				// 头像上传成功
				Helpers.showToast(MainActivity.this, "头像上传成功", Toast.LENGTH_SHORT);
				AppApplication.mHeadUrl = loginInfo.getPic_url();
				
				String url = AppApplication.mHeadUrl;
				
				String fileName = url.substring(url.lastIndexOf("=") + 1, url.length()) + ".png";
				File f = new File(FileDirProvider.icon, fileName);
				if (f.exists())
				{
					f.delete();
				}
				
				if(picPath != null && picPath.trim().length() != 0)
				{
					Drawable mDrawable = new BitmapDrawable(Helpers.scaleBitmap(picPath, 90, 90));
					if (mDrawable == null) {
						return;
					}
					headerView.setBackgroundDrawable(mDrawable);
				}
				break;
			case 7:
				// 头像上传失败
				Helpers.showToast(MainActivity.this, "头像上传失败", Toast.LENGTH_SHORT);
				finish();
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if(!isTakePicture)
		{
			initHeadAndName();
		}
		isTakePicture = false;
	}

	private void initHeadAndName() {
		if (AppApplication.mUserName != null) {
			((TextView) findViewById(R.id.main_username)).setText(AppApplication.mUserName);
		}else
		{
			((TextView) findViewById(R.id.main_username)).setText("游客");
			((TextView) findViewById(R.id.hr_letter_count)).setVisibility(View.GONE);
		}
		if (AppApplication.mHeadUrl != null) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					Helpers.downloadFile(MainActivity.this, AppApplication.mHeadUrl, mHandler);
				}
			}).start();
		}else
		{
			((ImageView) findViewById(R.id.main_head_img)).setBackgroundResource(R.drawable.head_pic_default);
		}
		
		if (AppApplication.hrLetterCount != null) {
			((TextView) findViewById(R.id.hr_letter_count)).setVisibility(View.VISIBLE);
			((TextView) findViewById(R.id.hr_letter_count)).setText("您有 " + AppApplication.hrLetterCount + " 封未读的人事来信");
		}
	}

	public void initView() {
		mBar = (TitleBar) findViewById(R.id.activity_title_bar);
		mBar.setTitleText("我的首页");
		mBar.setLeftBg(R.drawable.bg_nav_left_main);
		mBar.setRightBg(R.drawable.title_right_selector_main);
		mBar.back.setOnClickListener(this);
		mBar.right.setOnClickListener(this);

		headerView = (ImageView) findViewById(R.id.main_head_img);

		menu_1 = (FrameLayout) findViewById(R.id.menu_1);
		menu_2 = (FrameLayout) findViewById(R.id.menu_2);
		menu_3 = (FrameLayout) findViewById(R.id.menu_3);

		View menuOne = View.inflate(this, R.layout.menu_one, null);
		View menuTwo = View.inflate(this, R.layout.menu_two, null);
		View menuThree = View.inflate(this, R.layout.menu_three, null);

		LinearLayout.LayoutParams layoutParams = 
				new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1);
		menu_1.addView(menuOne,layoutParams);
		menu_2.addView(menuTwo,layoutParams);
		menu_3.addView(menuThree,layoutParams);

		setMenuListener(R.id.menu_img_01);
		setMenuListener(R.id.menu_img_02);
		setMenuListener(R.id.menu_img_03);
		setMenuListener(R.id.menu_img_04);
		setMenuListener(R.id.menu_img_07);
		setMenuListener(R.id.menu_img_08);
		setMenuListener(R.id.menu_img_10);
		setMenuListener(R.id.menu_img_11);
		setMenuListener(R.id.menu_img_12);
		setMenuListener(R.id.main_head_img);
		
		if(summaryWindow == null) {
			View view = View.inflate(this, R.layout.picture_pop, null);
			view.findViewById(R.id.takePictureFormAlbum).setOnClickListener(this);
			view.findViewById(R.id.takePictureFormCamera).setOnClickListener(this);
			view.findViewById(R.id.cancel).setOnClickListener(this);
			view.getBackground().setAlpha(240);
			summaryWindow = 
					new PopupWindow(view, 
							LayoutParams.FILL_PARENT, 
							dm.heightPixels / 12 * 5 );
		}
	}

	private void setMenuListener(int id) {
		((ImageView) findViewById(id)).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.main_head_img:
			if (!AppApplication.isLogin) 
			{
				Intent loginIntent = new Intent();
				loginIntent.setClass(MainActivity.this, LoginActivity.class);
				startActivity(loginIntent);
			}else
			{
				try {
					showPicturePop();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			break;
		case R.id.menu_img_01:
			// 找工作
			Intent findJobIntent = new Intent();
			findJobIntent.setClass(MainActivity.this, FindJobActivity.class);
			startActivity(findJobIntent);
			break;

		case R.id.menu_img_02:
			// 招聘会
			Intent jobFairIntent = new Intent();
			jobFairIntent.setClass(MainActivity.this, JobFairActivity.class);
			startActivity(jobFairIntent);
			break;

		case R.id.menu_img_03:
			// 人事来信
			if (AppApplication.isLogin) {
				// 已登录
				Intent hrLetterIntent = new Intent();
				hrLetterIntent.setClass(MainActivity.this, HrLetterActivity.class);
				startActivity(hrLetterIntent);
			} else {
				Intent loginIntent = new Intent();
				loginIntent.setClass(MainActivity.this, LoginActivity.class);
				startActivity(loginIntent);
			}
			break;

		case R.id.menu_img_04:
			// 工作收藏
			if (AppApplication.isLogin) {
				// 已登录
				Intent jobCollectIntent = new Intent();
				jobCollectIntent.setClass(MainActivity.this, JobCollectActivity.class);
				jobCollectIntent.putExtra("from", "collect");
				startActivity(jobCollectIntent);
			} else {
				Intent loginIntent = new Intent();
				loginIntent.setClass(MainActivity.this, LoginActivity.class);
				startActivity(loginIntent);
			}
			break;

		case R.id.menu_img_11:
			//人才引进
			Intent talentIntent = new Intent();
			talentIntent.setClass(MainActivity.this, TalentActivity.class);
			startActivity(talentIntent);
			break;
		case R.id.menu_img_10:
			// 人才资讯
			Intent newsIntent = new Intent();
			newsIntent.setClass(MainActivity.this, NewsActivity.class);
			startActivity(newsIntent);
			break;

		case R.id.menu_img_07:
			// 申请记录
			if (AppApplication.isLogin) {
				// 已登录
				Intent recordIntent = new Intent();
				recordIntent.setClass(MainActivity.this, JobCollectActivity.class);
				recordIntent.putExtra("from", "record");
				startActivity(recordIntent);
			} else {
				Intent loginIntent = new Intent();
				loginIntent.setClass(MainActivity.this, LoginActivity.class);
				startActivity(loginIntent);
			}
			break;
		case R.id.menu_img_08:
			// 档案查询
//			if (AppApplication.isLogin) {
				// 已登录
				Intent archivesIntent = new Intent();
				archivesIntent.setClass(MainActivity.this, ArchivesActivity.class);
				startActivity(archivesIntent);
//			} else {
//				Intent loginIntent = new Intent();
//				loginIntent.setClass(MainActivity.this, LoginActivity.class);
//				startActivity(loginIntent);
//			}
			break;

		case R.id.menu_img_12:
			// 户籍查询
			Intent censusIntent = new Intent();
			censusIntent.setClass(MainActivity.this, CensusActivity.class);
			startActivity(censusIntent);
			break;
		case R.id.tb_ibtn_right:
			// 设置
			Intent settingsIntent = new Intent();
			settingsIntent.setClass(MainActivity.this, SettingsActivity.class);
			startActivity(settingsIntent);
			break;
		case R.id.tb_ibtn_back:
		    startActivity(new Intent(MainActivity.this, ContactUsActivity.class));
		    break;
		case R.id.takePictureFormAlbum:
			Intent picture = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(picture, PICTURE);
		    break;
		case R.id.takePictureFormCamera:
			Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(camera, CAMERA);
		    break;
		case R.id.cancel:
			closePicturePop();
		    break;

		default:
			break;
		}
	}
	
	/**
	 * show summary window
	 */
	public void showPicturePop() {
		if(summaryWindow != null) {
			if(!summaryWindow.isShowing()) {
				summaryWindow.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM, 0, 0);
			}
		}
	}
	
	/**
	 * close summary window
	 */
	public void closePicturePop() {
		if(summaryWindow != null) {
			if(summaryWindow.isShowing()) {
				summaryWindow.dismiss();
			}
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		isTakePicture = true;
		closePicturePop();
		if(resultCode == Activity.RESULT_OK && null != data){
			String sdState=Environment.getExternalStorageState();
			   String dstPath = "";
			   if(!sdState.equals(Environment.MEDIA_MOUNTED)){
				   File dir = context.getDir("files", Context.MODE_PRIVATE);
				   dstPath = dir.getAbsolutePath();
			   }else
			   {
				   File file = new File(FileDirProvider.icon);
				   if(!file.exists())
				   {
					   file.mkdirs();
				   }
				   dstPath = file.getPath();
			   }
			   String name= DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + "";
			   Bitmap bmp = null;
			switch (requestCode) {
			case PICTURE:
				Uri selectedImage = data.getData();
			    String[] filePathColumns={MediaStore.Images.Media.DATA,MediaStore.Images.Media.ORIENTATION};
			    Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null,null, null);
			    c.moveToFirst();
			    int columnIndex = c.getColumnIndex(filePathColumns[0]);
			    String tmpPath = c.getString(columnIndex);
			    String orientation = c.getString(c.getColumnIndex(filePathColumns[1]));// 获取旋转的角度 
			    int angle = 0;  
	            if (orientation != null && !"".equals(orientation)) {  
	                angle = Integer.parseInt(orientation);  
	            }  
			    bmp = Helpers.scaleBitmap(tmpPath, 128, 128,angle);
			    
			    if (bmp != null) {
					FileOutputStream fout = null;
					   picPath= dstPath+ File.separator + name;
					   try {
					    fout = new FileOutputStream(picPath);
					    if(tmpPath.endsWith("jpg") || tmpPath.endsWith("jpeg"))
					    {
					    	bmp.compress(Bitmap.CompressFormat.JPEG, 100, fout);
					    }else
					    {
					    	bmp.compress(Bitmap.CompressFormat.PNG, 100, fout);
					    }
					    
					   } catch (FileNotFoundException e) {
					    e.printStackTrace();
					   }finally{
					    try {
					     fout.flush();
					     fout.close();
					    } catch (IOException e) {
					     e.printStackTrace();
					    }
					   }
				}
			    c.close();
				break;
			case CAMERA:
				   Bundle bundle = data.getExtras();
				   //获取相机返回的数据，并转换为图片格式
				   bmp = (Bitmap)bundle.get("data");
				   if (bmp != null) {
						FileOutputStream fout = null;
						   picPath= dstPath+ File.separator + name;
						   try {
						    fout = new FileOutputStream(picPath);
						    bmp.compress(Bitmap.CompressFormat.PNG, 100, fout);
						   } catch (FileNotFoundException e) {
						    e.printStackTrace();
						   }finally{
						    try {
						     fout.flush();
						     fout.close();
						    } catch (IOException e) {
						     e.printStackTrace();
						    }
						   }
					}
				break;

			default:
				break;
			}
			
			if(picPath != null && picPath.trim().length() != 0)
			{
				Map<String, String> params = new HashMap<String, String>();
				params.put("token", AppApplication.mToken);
				params.put("user_id", AppApplication.mUserID);
				params.put("pic", picPath);
				loginInfo = new UserInfo();
				String url = RequestUrlProvider.USER_UPLOAD_PIC;
				Object[] args = new Object[4];
				args[0] = mHandler;
				args[1] = url;
				args[2] = loginInfo;
				args[3] = params;
				Helpers.showToast(MainActivity.this, "正在上传头像", Toast.LENGTH_SHORT);
				new UploadPicTask().execute(args);
			}
			   
		}
	}
	
	@Override
    protected void onStart() {
        super.onStart();
        FlurryAgent.onStartSession(this, "QMXRD2F95Q6YGS4Z9MZ9");
    }

    @Override
    protected void onStop() {
        super.onStop();
        FlurryAgent.onEndSession(this);
    }
}